<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          clearable
          placeholder="请输入企业名称"
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-input
          v-model="queryParams.contacts"
          clearable
          placeholder="请输入联系人"
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="queryParams.phone"
          clearable
          placeholder="请输入联系方式"
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="single"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="handleUpdate"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
        >
          批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :loading="exportLoading"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >
          导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :loading="exportLoading"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >
          导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          plain
          size="mini"
          type="danger"
          @click="downloadExport()"
        >
          模板下载
        </el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column :show-overflow-tooltip="true" align="center" label="企业名称" prop="id" />
      <el-table-column align="center" label="企业信用代码" prop="configName" />
      <el-table-column align="center" label="所属区域" prop="configKey" />
      <el-table-column align="center" label="联系人" prop="configValue" />
      <el-table-column :formatter="typeFormat" align="center" label="联系方式" prop="configType" />
      <el-table-column align="center" label="邮箱" prop="remark" />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:config:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['system:config:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pagesize"
      :page.sync="queryParams.pagenum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" maxlength="20" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="企业信用代码" prop="enterpriseCreditCode">
          <el-input v-model="form.enterpriseCreditCode" maxlength="18" placeholder="请输入企业信用代码" />
        </el-form-item>
        <el-form-item label="所属区域" prop="region">
          <el-input v-model="form.region" maxlength="10" placeholder="请输入所属区域" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" maxlength="10" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" maxlength="11" placeholder="请输入联系方式" type="textarea" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">
          确 定
        </el-button>
        <el-button @click="cancel">
          取 消
        </el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" append-to-body width="400px">
      <el-upload
        ref="upload"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :data="upload.data"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        class="upload-demo"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          只能上传xls、xlsx格式文件，且不超过2MB
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">
          确 定
        </el-button>
        <el-button @click="upload.open = false">
          取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth"
import {
  saveSample,
  deleteSample,
  exportConfig,
  sampleDetail,
  getSampleList,
  refreshCache,
  updateSample
} from '@/api/sampleCenterManagement'
export default {
  name: 'Config',
  components:{
  },
  data() {
    let handleName = (rule, value, callback) => {
      let validator ='^[A-Za-z0-9\u4e00-\u9fa5]+$'
      if (value) {
        if(!new RegExp(validator).test(value)){
          callback(new Error('请输入中英文+阿拉伯数字格式'))
        }else{
          callback()
        } 
      }else{
        callback(new Error('企业名称不能为空'))
      }
        
    }
    let handleCreditCode = (rule, value, callback) => {
      let validator ='^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{18}$'
      if (value) {
        if(!new RegExp(validator).test(value)){
          callback(new Error('请输入正确的格式'))
        }else{
          callback()
        } 
      }else{
          callback()
        } 
    }
    let handleRegion = (rule, value, callback) => {
      let validator ='^[\u4e00-\u9fa5]+$'
      if (value) {
        if(!new RegExp(validator).test(value)){
          callback(new Error('请输入中文格式'))
        }else{
          callback()
        } 
      }else{
        callback(new Error('所属区域不能为空'))
      }
    }
    let handlePhone = (rule, value, callback) => {
      let validator ='^1[3-9][0-9]{9}$'
      if (value) {
        if(!new RegExp(validator).test(value)){
          callback(new Error('请输入11位阿拉伯数字'))
        }else{
          callback()
        } 
      }else{
        callback(new Error('联系方式不能为空'))
      }
    }
    let handleContacts = (rule, value, callback) => {
      let validator ='^[\u4e00-\u9fa5a-zA-Z]+$'
      if (value) {
        if(!new RegExp(validator).test(value)){
          callback(new Error('请输入中英文格式'))
        }else{
          callback()
        } 
      }else{
        callback(new Error('联系人不能为空'))
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pagenum: 1,
        pagesize: 10,
        enterpriseName: undefined,
        contacts: undefined,
        phone: undefined,
      },
      // 问卷参数
      form: {},
      // 问卷校验
      rules: {
        enterpriseName: [
          {required: true, validator:handleName, trigger: 'blur'}
        ],
        enterpriseCreditCode: [
          {validator:handleCreditCode, trigger: 'blur'}
        ],
        region: [
          {required: true, validator:handleRegion, trigger: 'blur'}
        ],
        contacts: [
          {required: true, validator:handleContacts, trigger: 'blur'}
        ],
        phone: [
          {required: true, validator:handlePhone, trigger: 'blur'}
        ]
      },
      upload: {
        // 是否显示弹出层
        open: true,
        // 弹出层标题
        title: '导入',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        data:{
          formKey: ''
        },
        // 设置上传的请求头部
        headers: {Authorization: 'Bearer ' + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_API_ROOT + '/user/form/data/import'
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_yes_no').then((response) => {
      this.typeOptions = response.data
    })
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true
      getSampleList(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
          this.configList = response.data.records
          this.total = response.data.total
          this.loading = false
        }
      )
    },
    // 参数系统内置字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.configType)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 问卷重置
    reset() {
      this.form = {
        name: undefined,
        creditCode: undefined,
        region: undefined,
        contacts: undefined,
        phone: undefined,
        email: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pagenum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      sampleDetail(id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateSample(this.form).then((response) => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            saveSample(this.form).then((response) => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        deleteSample(ids).then((res) => {
          if(res.code==0){
            var pageSize =Math.ceil((this.total-1)/this.queryParams.pagesize)
            if(pageSize < this.queryParams.pagenum){
                this.queryParams.pagenum = pageSize
            }
            this.msgSuccess('删除成功')
            this.getList()
          }else{
            this.msgError(res.msg)
          }
          
        })
        // return deleteSample(ids)
      }).then(() => {
        // this.getList()
        // this.msgSuccess('删除成功')
      }).catch(() => {
        
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有样本?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportConfig(queryParams).then((res) => {
          this.download(res, '系统配置')
          this.exportLoading = false
        })
      })
    },
    // 下载模板
    downloadExport(url){
      const elink = document.createElement('a')
      elink.style.display = 'none'
      elink.href = url
      var name = this.formName.replace(/<[^>]+>/g, '')
      elink.download=name+'_'+this.formatDate(new Date())+'.zip'
      console.log(elink.download,'elink.download')
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.msgSuccess('刷新成功')
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.data, '导入结果', {dangerouslyUseHTMLString: true})
      this.$emit('success')
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
